package com.yizisu.playerlibrary.view.video_view.helper

import android.animation.ValueAnimator
import com.yizisu.playerlibrary.impl.exoplayer.mainHandler

/**
 * 隐藏或者展示的动画控制器
 */
class PlayerControllerBarHelper(private val playerConfig: IPlayerConfig) {
    companion object {
        const val DEFAULT_DELAY_DURATION = 4000L
    }

    private val view = mainHandler

    private var isShow = playerConfig.showOrHideControllerData.value == 1f

    private val showOrHideAnim by lazy {
        ValueAnimator.ofFloat().apply {
            duration = 200
            addUpdateListener {
                val currentValue = it.animatedValue as Float
                playerConfig.updateShowOrHideController(currentValue)
            }
        }
    }

    private val showRunnable = ShowOrHideRunnable(1f)

    private val hideRunnable = ShowOrHideRunnable(0f)

    fun show(delay: Long) {
        showOrHide(showRunnable, delay)
    }

    fun hide(delay: Long) {
        showOrHide(hideRunnable, delay)
    }

    fun hideIfShow(delay: Long) {
        if (isShow) {
            hide(delay)
        }
    }

    fun autoShowOrHide() {
        if (isShow) {
            hide(0)
        } else {
            show(0)
            hide(DEFAULT_DELAY_DURATION)
        }
    }

    private fun showOrHide(runnable: Runnable, delay: Long) {
        view.removeCallbacks(showRunnable)
        view.removeCallbacks(hideRunnable)
        if (delay <= 0L) {
            runnable.run()
        } else {
            view.postDelayed(runnable, delay)
        }
    }

    private inner class ShowOrHideRunnable(private val endValue: Float) : Runnable {
        override fun run() {
            val currentValue = playerConfig.showOrHideControllerData.value
            if (currentValue != null && currentValue != endValue) {
                showOrHideAnim.cancel()
                showOrHideAnim.setFloatValues(currentValue, endValue)
                showOrHideAnim.start()
                if (endValue == 1f) {
                    isShow = true
                }
                if (endValue == 0f) {
                    isShow = false
                }
            }
        }
    }
}